package org.kalai.unifypay.tfb.pay;

import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.kalai.unifypay.Constant;
import org.kalai.unifypay.util.CommonUtil;
import org.kalai.unifypay.util.DateUtil;
import org.kalai.unifypay.util.HttpUtil;


/**
 * 天付宝公众号支付
 * 
 * @author nicholas
 *
 */
public class TFBPublicPayService {

	private static final Logger log = Logger.getLogger(TFBPublicPayService.class);

	public static Map<String, Object> publicPay(String sp_billno, String pay_type, int tran_amt) {

		String serviceUrl = Constant.TFB_SERVICE_URL + "api_ali_pay_apply.cgi";
		String spid = null;
		String secretKey = null;

		TreeMap<String, Object> params = new TreeMap<String, Object>();
		params.put("spid", spid);// 商户号
		params.put("notify_url", Constant.TFB_NOTIFY_URL);// 异步通知
		params.put("sp_billno", sp_billno);// 商户订单号
		params.put("spbill_create_ip", "101.67.157.147");// 商户ip
		params.put("pay_type", pay_type);// 支付类型(扫码支付:800201)
		params.put("tran_time", DateUtil.formatNow("yyyyMMddhhmmss"));// 发起交易时间
		params.put("tran_amt", tran_amt);// 交易金额(单位为分)
		params.put("cur_type", "CNY");// 币种类型
		// 加入协议参数
		TFBUtils.sign(params, secretKey);

		String result = HttpUtil.sendHttpsPost(serviceUrl, params);
		System.out.println(result);
		Map<String, String> resultMap = TFBUtils.xmlToMap(result);
		String respCode = resultMap.get("retcode");
		String respMsg = resultMap.get("retmsg");
		Map<String, Object> respMap = CommonUtil.createRespMap(respCode.equals("0") ? "00" : respCode, respMsg);
		if (respCode.equals("0")) {
			respMap.put("respDesc", "订单创建成功");
			respMap.put("codeUrl", resultMap.get("qrcode"));
		} else {
			log.error(String.format("(天付宝)公众号支付失败:[resultMap=%s]", resultMap));
		}
		return respMap;
	}

}
